using System;
using System.Management;

namespace AUSRIS.Reports.Extensions.Security.Authentication
{
    internal sealed class ReportServerUtility
    {
        internal static string GetReportServerUrl(string machineName)
        {
            string reportServerUrl = String.Empty;
            string wmiNamespace = @"\\" + machineName + @"\root\Microsoft\SqlServer\ReportServer\v9";
            ManagementScope managementScope = null;
            ConnectionOptions connectionOptions = new ConnectionOptions();
            connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;

            try
            {
                managementScope = new ManagementScope(wmiNamespace, connectionOptions);
                managementScope.Connect();
                ManagementPath managementPath = new ManagementPath("MSReportServer_Instance");
                ManagementClass managementClass = new ManagementClass(managementScope, managementPath, new ObjectGetOptions());
                managementClass.Get();

                if(managementClass == null)
                {
                    throw new Exception("No WMI class found.");
                }

                foreach(ManagementObject managementObject in managementClass.GetInstances())
                {
                    managementObject.Get();
                    reportServerUrl = (string)managementObject["ReportServerUrl"];
                }
            }
            catch(Exception ex)
            {
                throw new Exception("An error occurred while attempting to get the ReportServer Url.", ex);
            }

            return reportServerUrl + @"/ReportService2005.asmx";
        }
    }
}
